package in.muton.edushare.newentities.upgraded.singleInvite;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.newentities.DeptUserCreator;
import in.muton.edushare.newentities.upgraded.InviteUtils;
import in.muton.edushare.wicket.models.CayenneList;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.model.IModel;

import com.edushare.common.dao.BatchDAO;
import com.edushare.common.dao.UserDeptLinkDAO;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.Batches;
import com.edushare.common.vo.Departments;
import com.edushare.common.vo.UserDeptLink;
import com.edushare.common.vo.Users;

public class BatchInvite implements SingleAudienceInvite {
	private static final long serialVersionUID = -1099950841522164468L;
	private IModel<Batches> batchModel;

	public BatchInvite(IModel<Batches> batchModel) {
		this.batchModel = batchModel;
	}

	public List<String> inviteUsers(int role, CayenneList<Users> userList,
			ORMInterface ormInterface) {
		List<String> statusString = new ArrayList<String>();
		List<IModel<Users>> userModels = userList.getObject();
		BatchDAO bDAO = new BatchDAO(ormInterface);
		for (IModel<Users> u : userModels) {
			new UserDeptLinkDAO(ormInterface).addUser(batchModel.getObject()
					.getCurricula().getDepartment(), u.getObject(), role);
			statusString.add(bDAO.addUserFB(batchModel.getObject(), u
					.getObject()));
		}
		return statusString;
	}

	public List<String> inviteUsers(int role,
			List<CayenneList<Users>> userList, ORMInterface ormInterface) {
		List<String> strList = new ArrayList<String>();
		for (CayenneList<Users> u : userList) {
			strList.addAll(inviteUsers(role, u, ormInterface));
		}
		return strList;
	}

	public List<String> inviteUsers(int role, String[] userList,
			ORMInterface ormInterface) {
		List<String> statusString = new ArrayList<String>();
		BatchDAO bDAO = new BatchDAO(ormInterface);

		DeptUserCreator duc = new DeptUserCreator(EduShareSession.get()
				.getSessionORMInterface(), new CayenneModel<Departments>(
				batchModel.getObject().getCurricula().getDepartment()),
				UserDeptLink.STUDENT);

		for (String u : userList) {
			Users userVO = InviteUtils.getUserByString(u, ormInterface);
			if (userVO != null) {
				duc.addUsersToDept(u);
				statusString
						.add(bDAO.addUserFB(batchModel.getObject(), userVO));
			} else {
				if (InviteUtils.isEmailId(u)) {
					duc.addUsersToDept(u);
					userVO = InviteUtils.getUserByString(u, ormInterface);
					if (userVO != null) {
						statusString.add(bDAO.addUserFB(batchModel.getObject(),
								userVO));
					} else {
						statusString.add("Unable to invite user " + u
								+ " due to unknown error.");
					}
				} else {
					statusString.add("Unable to determine the type of " + u);
				}
			}
		}
		return statusString;
	}

}
